﻿Imports DotNetNuke
Imports DotNetNuke.Common
Imports DotNetNuke.Security
Imports DotNetNuke.Entities.Profile
Imports DotNetNuke.Entities.Users
Imports DotNetNuke.Entities.Users.UserProfile
Imports System.Web.UI
Imports Telerik.Web.UI
Imports DotNetNuke.Security.Membership
Imports DotNetNuke.Services.Mail
Imports DotNetNuke.Security.Roles

Namespace dnnWerk.Modules.Users

    Partial Class uc_Profile
        Inherits UserModuleBase

        Private blnPageNeedsToPostback As Boolean = False

#Region "Event Handlers"

        Protected Sub Page_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init

            DotNetNuke.Framework.AJAX.RegisterScriptManager()

            ProcessFormTemplate(plhProfile, Template_UserProfile(CurrentLocale), User, blnPageNeedsToPostback)

            Dim btnUpdate As Button = CType(FindControlRecursive(plhProfile, plhProfile.ID & "_" & Constants.ControlId_UpdateButton), Button)
            If Not btnUpdate Is Nothing Then

                AddHandler btnUpdate.Click, AddressOf btnUpdate_Click

                If blnPageNeedsToPostback Then
                    DotNetNuke.Framework.AJAX.RegisterPostBackControl(btnUpdate)
                End If

            End If

            Dim btnDelete As Button = CType(FindControlRecursive(plhProfile, plhProfile.ID & "_" & Constants.ControlId_DeleteButton), Button)
            If Not btnDelete Is Nothing Then

                AddHandler btnDelete.Click, AddressOf btnDelete_Click

            End If

        End Sub

        Protected Sub btnUpdate_Click(ByVal sender As Object, ByVal e As System.EventArgs)
            UpdateProfile()
        End Sub

        Protected Sub btnDelete_Click(ByVal sender As Object, ByVal e As System.EventArgs)
            DeleteAccount()
        End Sub

        Protected Sub Page_PreRender(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.PreRender

            ManageRegionLabel(Me.plhProfile)

        End Sub

#End Region

#Region "Private Methods"

        Private Sub UpdateProfile()

            pnlSuccess.Visible = False
            pnlError.Visible = False

            Dim strMessage As String = ""
            Dim strUpdated As String = ""

            Dim blnUpdateUsername As Boolean = False
            Dim blnUpdateFirstname As Boolean = False
            Dim blnUpdateLastname As Boolean = False
            Dim blnUpdateDisplayname As Boolean = False
            Dim blnUpdatePassword As Boolean = False
            Dim blnUpdateEmail As Boolean = False

            Dim txtUsername As TextBox = CType(FindControlRecursive(plhProfile, plhProfile.ID & "_" & Constants.ControlId_Username), TextBox)
            blnUpdateUsername = (Not txtUsername Is Nothing)

            If blnUpdateUsername AndAlso IsRegisterMode() Then
                If Not IsValidUserAttribute(Constants.User_Username, plhProfile) Then
                    strMessage += "Error"
                    AddErrorIndicator(Constants.User_Username, plhProfile)
                Else
                    RemoveErrorIndicator(Constants.User_Username, plhProfile, True)
                End If
            End If

            Dim txtEmail As TextBox = CType(FindControlRecursive(plhProfile, plhProfile.ID & "_" & Constants.ControlId_Email), TextBox)
            blnUpdateEmail = (Not txtEmail Is Nothing)

            If blnUpdateEmail Then
                If Not IsValidUserAttribute(Constants.User_Email, plhProfile) Then
                    strMessage += "Error"
                    AddErrorIndicator(Constants.User_Email, plhProfile)
                Else
                    RemoveErrorIndicator(Constants.User_Email, plhProfile, True)
                End If
            End If

            Dim txtPassword As TextBox = CType(FindControlRecursive(plhProfile, plhProfile.ID & "_" & Constants.ControlId_Password1), TextBox)
            Dim txtPassword2 As TextBox = CType(FindControlRecursive(plhProfile, plhProfile.ID & "_" & Constants.ControlId_Password2), TextBox)
            blnUpdatePassword = (Not txtPassword Is Nothing AndAlso Not txtPassword2 Is Nothing)

            If blnUpdatePassword Then
                If txtPassword.Text = "" AndAlso txtPassword2.Text = "" Then
                    blnUpdatePassword = False
                End If
            End If

            If blnUpdatePassword Then
                If Not IsValidUserAttribute(Constants.User_Password1, plhProfile) Then
                    strMessage += "Error"
                    AddErrorIndicator(Constants.User_Password1, plhProfile)
                Else
                    RemoveErrorIndicator(Constants.User_Password1, plhProfile, True)
                End If
                If Not IsValidUserAttribute(Constants.User_Password2, plhProfile) Then
                    strMessage += "Error"
                    AddErrorIndicator(Constants.User_Password2, plhProfile)
                Else
                    RemoveErrorIndicator(Constants.User_Password2, plhProfile, True)
                End If
            End If

            Dim txtFirstName As TextBox = CType(FindControlRecursive(plhProfile, plhProfile.ID & "_" & Constants.ControlId_Firstname), TextBox)
            blnUpdateFirstname = (Not txtFirstName Is Nothing)

            If blnUpdateFirstname Then
                If Not IsValidUserAttribute(Constants.User_Firstname, plhProfile) Then
                    strMessage += "Error"
                    AddErrorIndicator(Constants.User_Firstname, plhProfile)
                Else
                    RemoveErrorIndicator(Constants.User_Firstname, plhProfile, True)
                End If
            End If

            Dim txtLastName As TextBox = CType(FindControlRecursive(plhProfile, plhProfile.ID & "_" & Constants.ControlId_Lastname), TextBox)
            blnUpdateLastname = (Not txtLastName Is Nothing)

            If blnUpdateLastname Then
                If Not IsValidUserAttribute(Constants.User_Lastname, plhProfile) Then
                    strMessage += "Error"
                    AddErrorIndicator(Constants.User_Lastname, plhProfile)
                Else
                    RemoveErrorIndicator(Constants.User_Lastname, plhProfile, True)
                End If
            End If

            Dim txtDisplayName As TextBox = CType(FindControlRecursive(plhProfile, plhProfile.ID & "_" & Constants.ControlId_Displayname), TextBox)
            blnUpdateDisplayname = (Not txtDisplayName Is Nothing)

            If blnUpdateDisplayname Then
                If Not IsValidUserAttribute(Constants.User_Displayname, plhProfile) Then
                    strMessage += "Error"
                    AddErrorIndicator(Constants.User_Displayname, plhProfile)
                Else
                    RemoveErrorIndicator(Constants.User_Displayname, plhProfile, True)
                End If
            End If

            For Each itemProp As String In GetPropertiesFromTempate(Template_UserProfile(CurrentLocale))
                Try
                    Dim prop As ProfilePropertyDefinition = ProfileController.GetPropertyDefinitionByName(PortalId, itemProp.Substring(2)) 'itemprop comes in the form U:Propertyname or P:Propertyname
                    If Not prop Is Nothing Then
                        If Not IsValidProperty(UserInfo, prop, plhProfile) Then
                            strMessage += "Error"
                            AddErrorIndicator(prop.PropertyDefinitionId.ToString, plhProfile)
                        Else
                            RemoveErrorIndicator(prop.PropertyDefinitionId.ToString, plhProfile, prop.Required)
                        End If
                    End If
                Catch
                End Try
            Next

            If strMessage.Length > 0 Then
                Me.pnlError.Visible = True
                Me.lblError.Text = "<ul><li>" & Localization.GetString("FillInAll", Me.SharedResourcefile) & "</li></ul>"
                Exit Sub
            End If

            Dim oUser As UserInfo = UserController.GetCurrentUserInfo
            Dim oldAccount As UserInfo = UserController.GetCurrentUserInfo

            If blnUpdateEmail Then
                oUser.Email = txtEmail.Text
                If oUser.Email <> oldAccount.Email Then
                    strUpdated += Localization.GetString("Email", SharedResourcefile) & ", "
                End If
            End If

            'try updating password
            If blnUpdatePassword Then
                If txtPassword.Text = txtPassword2.Text Then
                    If UserController.ValidatePassword(txtPassword.Text) Then
                        UserController.ChangePassword(oUser, "", txtPassword.Text)
                        strUpdated += Localization.GetString("Password", SharedResourcefile) & ", "
                    Else
                        Me.pnlError.Visible = True
                        Me.lblError.Text = "<ul><li>" & Localization.GetString("InvalidPassword.Text", SharedResourcefile) & "</li></ul>"
                        Exit Sub
                    End If
                Else
                    Me.pnlError.Visible = True
                    Me.lblError.Text = "<ul><li>" & Localization.GetString("PasswordsDontMatch.Text", SharedResourcefile) & "</li></ul>"
                    Exit Sub
                End If
            End If

            UpdateProfileProperties(plhProfile, oUser, strUpdated, GetPropertiesFromTempate(Template_UserProfile(CurrentLocale)))

            'make sure first and lastname are in sync with user and profile object
            If blnUpdateFirstname = True Then
                If oldAccount.FirstName <> txtFirstName.Text Then
                    strUpdated += Localization.GetString("Firstname", SharedResourcefile) & ", "
                End If
                oUser.Profile.FirstName = txtFirstName.Text
                oUser.FirstName = txtFirstName.Text
            Else
                If oUser.Profile.FirstName <> "" Then
                    oUser.FirstName = oUser.Profile.FirstName
                End If
            End If

            If blnUpdateLastname = True Then
                If oldAccount.LastName <> txtLastName.Text Then
                    strUpdated += Localization.GetString("Lastname", SharedResourcefile) & ", "
                End If
                oUser.Profile.LastName = txtLastName.Text
                oUser.LastName = txtLastName.Text
            Else
                If oUser.Profile.LastName <> "" Then
                    oUser.LastName = oUser.Profile.LastName
                End If
            End If

            If blnUpdateDisplayname Then
                If oldAccount.DisplayName <> txtDisplayName.Text Then
                    strUpdated += Localization.GetString("Displayname", SharedResourcefile) & ", "
                End If
                oUser.DisplayName = txtDisplayName.Text
            Else
                Select Case DisplaynameMode
                    Case DisplaynameUpdateMode.Email
                        If blnUpdateEmail Then
                            oUser.DisplayName = txtEmail.Text.Trim
                        End If
                    Case DisplaynameUpdateMode.FirstLetterLastname
                        If blnUpdateLastname AndAlso blnUpdateFirstname Then
                            oUser.DisplayName = oUser.FirstName.Trim.Substring(0, 1) & ". " & oUser.LastName
                        End If
                    Case DisplaynameUpdateMode.FirstnameLastname
                        If blnUpdateLastname AndAlso blnUpdateFirstname Then
                            oUser.DisplayName = oUser.FirstName & " " & oUser.LastName
                        End If
                    Case DisplaynameUpdateMode.Lastname
                        If blnUpdateLastname Then
                            oUser.DisplayName = oUser.LastName
                        End If
                End Select
            End If

            'update profile
            UserController.UpdateUser(PortalId, oUser)

            'add to role
            If AddToRoleOnSubmit <> Null.NullInteger Then
                Try
                    Dim rc As New Security.Roles.RoleController
                    rc.AddUserRole(PortalId, oUser.UserID, AddToRoleOnSubmit, Null.NullDate)
                Catch
                End Try
            End If

            'remove from role
            If RemoveFromRoleOnSubmit <> Null.NullInteger Then
                Try
                    Dim rc As New Security.Roles.RoleController
                    Dim r As RoleInfo = rc.GetRole(RemoveFromRoleOnSubmit, PortalId)

                    RoleController.DeleteUserRole(oUser, r, PortalSettings, False)
                Catch
                End Try
            End If

            'notify admin   
            If NotifyAddress <> "" AndAlso strUpdated.Length > 0 Then

                Dim strBody As String = Template_Email_ProfileUpdate_Admin(CurrentLocale)

                strBody = strBody.Replace("[PORTALURL]", PortalSettings.PortalAlias.HTTPAlias)
                strBody = strBody.Replace("[PORTALNAME]", PortalSettings.PortalName)
                strBody = strBody.Replace("[USERID]", oUser.UserID)
                strBody = strBody.Replace("[DISPLAYNAME]", oUser.DisplayName)
                strBody = strBody.Replace("[PASSWORD]", MembershipProvider.Instance().GetPassword(oUser, ""))
                strBody = strBody.Replace("[USERNAME]", oUser.Username)
                strBody = strBody.Replace("[FIRSTNAME]", oUser.FirstName)
                strBody = strBody.Replace("[LASTNAME]", oUser.LastName)
                strBody = strBody.Replace("[UPDATED]", strUpdated.Substring(0, strUpdated.LastIndexOf(",")).Replace(":", ""))
                strBody = strBody.Replace("[USERURL]", NavigateURL(UsermanagementTab, "", "uid=" & oUser.UserID.ToString))

                Try
                    Services.Mail.Mail.SendMail(PortalSettings.Email, NotifyAddress, "", String.Format(Localization.GetString("NotifySubject_ProfileUpdate", SharedResourcefile), PortalSettings.PortalName), strBody, "", "HTML", "", "", "", "")
                Catch
                End Try

            End If

            If NotifyUser AndAlso strUpdated.Length > 0 Then

                Dim strBody As String = Template_Email_ProfileUpdate_User(oUser.Profile.PreferredLocale)

                strBody = strBody.Replace("[PORTALURL]", PortalSettings.PortalAlias.HTTPAlias)
                strBody = strBody.Replace("[PORTALNAME]", PortalSettings.PortalName)
                strBody = strBody.Replace("[USERID]", oUser.UserID)
                strBody = strBody.Replace("[DISPLAYNAME]", oUser.DisplayName)
                strBody = strBody.Replace("[PASSWORD]", MembershipProvider.Instance().GetPassword(oUser, ""))
                strBody = strBody.Replace("[USERNAME]", oUser.Username)
                strBody = strBody.Replace("[FIRSTNAME]", oUser.FirstName)
                strBody = strBody.Replace("[LASTNAME]", oUser.LastName)
                strBody = strBody.Replace("[UPDATED]", strUpdated.Substring(0, strUpdated.LastIndexOf(",")).Replace(":", ""))
                strBody = strBody.Replace("[USERURL]", NavigateURL(TabId))

                Try
                    Services.Mail.Mail.SendMail(PortalSettings.Email, oUser.Email, "", String.Format(Localization.GetString("NotifySubject_ProfileUpdate", SharedResourcefile), PortalSettings.PortalName), strBody, "", "HTML", "", "", "", "")
                Catch
                End Try

            End If

            lblSucess.Text = "<ul><li>" & Localization.GetString("ProfileUpdateSuccess.Text", SharedResourcefile) & "</li></ul>"
            pnlSuccess.Visible = True

            If Not Request.QueryString("ReturnURL") Is Nothing Then
                Response.Redirect(Request.QueryString("ReturnURL"), True)
            End If

            If RedirectAfterSubmit <> "" Then
                Response.Redirect(RedirectAfterSubmit, True)
            End If

        End Sub

        Private Sub DeleteAccount()

            Dim oUser As UserInfo = UserController.GetCurrentUserInfo

            If UserController.DeleteUser(oUser, False, False) Then
                lblSucess.Text = "<ul><li>" & Localization.GetString("AccountDeleted.Text", SharedResourcefile) & "</li></ul>"
                pnlSuccess.Visible = True
            Else
                lblError.Text = "<ul><li>" & Localization.GetString("AccountNotDeleted.Text", SharedResourcefile) & "</li></ul>"
                pnlError.Visible = True
            End If

        End Sub

        'todo: lookup in membershipsetting
        Public Function MinPasswordLength() As String
            Return "7"
        End Function

        Public Function ErrorImageUrl() As String
            Return (Me.ModuleDirectory & "/images/error.png").Replace("~", "")
        End Function

        Public Function AcceptImageUrl() As String
            Return (Me.ModuleDirectory & "/images/accept.png").Replace("~", "")
        End Function

        Public Function Password1Id() As String
            Dim txtPassword As TextBox = CType(FindControlRecursive(plhProfile, plhProfile.ID & "_" & Constants.ControlId_Password1), TextBox)
            If Not txtPassword Is Nothing Then
                Return txtPassword.ClientID
            End If
            Return ""
        End Function

#End Region

        Protected Sub ctlAjax_AjaxRequest(ByVal sender As Object, ByVal e As Telerik.Web.UI.AjaxRequestEventArgs) Handles ctlAjax.AjaxRequest

            Dim cmd As String = e.Argument.Split(Char.Parse("|"))(0)
            Dim value As String = e.Argument.Split(Char.Parse("|"))(1)

            If cmd.ToLower = "validate_email" Then

                If IsValidEmail(value) Then

                    AddSuccessIndicator(Constants.User_Email, plhProfile)

                    'focus next control
                    Dim blnEmailFound As Boolean = False
                    For Each ctl As Control In plhProfile.Controls
                        Try
                            If blnEmailFound Then
                                Dim strId As String = ctl.ID
                                Dim ctlIdentifier As String = plhProfile.ID & "_ctl"
                                If strId.StartsWith(ctlIdentifier) Then
                                    'must be a register control
                                    ctlAjax.ResponseScripts.Add("focusControl('" & ctl.ClientID & "');")
                                    Exit For
                                End If
                            End If
                            If ctl.ID = plhProfile.ID & "_" & Constants.ControlId_Email Then
                                blnEmailFound = True
                            End If
                        Catch
                        End Try
                    Next

                Else

                    Dim txtEmail As TextBox = CType(FindControlRecursive(plhProfile, plhProfile.ID & "_" & Constants.ControlId_Email), TextBox)
                    AddErrorIndicator(Constants.User_Email, plhProfile)
                    CType(FindControlRecursive(plhProfile, plhProfile.ID & "_RESX_USERHELP_Email"), Literal).Text = Localization.GetString("InvalidEmail.Text", SharedResourcefile)
                    If Not txtEmail Is Nothing Then
                        ctlAjax.ResponseScripts.Add("focusControl('" & txtEmail.ClientID & "');")
                    End If

                End If

            End If

        End Sub

    End Class

End Namespace
